//
//  VisitInfoViewController.m
//  YunGui
//
//  Created by wmm on 16/3/24.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "VisitInfoViewController.h"
#import "VisitRecordTableViewCell.h"
#import "AddRecordViewController.h"
#import "VisitRecordModel.h"
#import "SJAvatarBrowser.h"
#import "RecordDetailViewController.h"

const CGFloat TableCellHeight2 = 190.0f +10;

@interface VisitInfoViewController ()<UITableViewDataSource,UITableViewDelegate,TableViewRecordDelegate,UIViewPassValueDelegate>
{
    
    NSArray      *_labelArray;
    BOOL isOpen;

    NSIndexPath *selectedIndex;
    
    CGRect bounds;
    
    NSMutableArray * rowHight;//行高
    NSMutableArray *bCheck;   // 所点按钮
    UIButton *addBtn;
    
    
}

@property(nonatomic,strong)UILabel *subNameLab;
@property(nonatomic,strong)UILabel *contactLab;
@property(nonatomic,strong)UILabel *phoneLab;
@property(nonatomic,strong)UILabel *areaLab;
@property(nonatomic,strong)UILabel *addressLab;
@property(nonatomic,strong)UILabel *proNameLab;
@property(nonatomic,strong)UILabel *opponentLab;
@property(nonatomic,strong)UITableView *visitRecordTableView;

@property(nonatomic,strong)NSMutableArray *visitRecordArray;

@end

@implementation VisitInfoViewController

- (void)viewWillDisappear:(BOOL)animated
{
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = @"拜访详情";
    self.navigationItem.leftBarButtonItem=[ViewTool getBackBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    self.navigationItem.rightBarButtonItem.customView.hidden=YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initViews];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [_visitRecordTableView reloadData];
}

- (void)initViews{
    
    rowHight   =[NSMutableArray array];
    bCheck =[NSMutableArray array];
    
    bounds=self.view.frame;
    
    CGFloat startX = [UIView getWidth:20];
    CGFloat imgW = 20;
    CGFloat labX = startX + imgW +15;
    CGFloat labH = 40;
    CGFloat labY = 10;
    CGFloat height = labH - 2*labY;
    CGFloat grayH = 15;
    CGFloat labW  = 80;
    CGFloat tfX = labX + labW +[UIView getWidth:5];
    CGFloat tfW = kScreenWidth - tfX - [UIView getWidth:15];
    
    _labelArray=@[@"小区名称",@"所属地区",@"具体地址",@"物业名称",@"竞争对手"];
    
    UIView *sectionView1 = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, grayH) withBackgroudColor:GrayBackColor];
    [self.view addSubview:sectionView1];
    
    UIView *line = [self getLineWith:CGRectMake(0, sectionView1.maxY - 1, kScreenWidth, 1)];
    [self.view addSubview:line];
    
    UIImageView *basicImg = [self imageWith:CGRectMake(startX, line.maxY+ labY, imgW, imgW) withName:@"Btn_Normal_Xinxi"];
    [self.view addSubview:basicImg];
    
    UILabel *basicLabel = [self getLabelWith:CGRectMake(labX, line.maxY + labY, labW, height) WithTitle:@"基本信息"];
    [self.view addSubview:basicLabel];
    
    UIView *line1 = [self getLineWith:CGRectMake(labX, basicLabel.maxY + labY - 1, kScreenWidth-labX, 1)];
    [self.view addSubview:line1];
    
    for (int i=0; i<_labelArray.count; i++) {
        UILabel *label = [self getLabelWith:CGRectMake(labX, line1.maxY + labY+ i*(height+5), labW, height) WithTitle:_labelArray[i] WithFontSize:14.0f WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentLeft];
        [self.view addSubview:label];
    }
    _subNameLab = [self getLabelWith:CGRectMake(tfX, line1.maxY + labY, tfW, height) WithTitle:@""];
    [self.view addSubview:_subNameLab];
    
    _areaLab = [self getLabelWith:CGRectMake(tfX, _subNameLab.maxY + 5, tfW, height) WithTitle:@""];
    [self.view addSubview:_areaLab];
    
    _addressLab = [self getLabelWith:CGRectMake(tfX, _areaLab.maxY + 5, tfW, height) WithTitle:@""];
    [self.view addSubview:_addressLab];
    
    _proNameLab = [self getLabelWith:CGRectMake(tfX, _addressLab.maxY + 5, tfW, height) WithTitle:@""];
    [self.view addSubview:_proNameLab];
    
    _opponentLab = [self getLabelWith:CGRectMake(tfX, _proNameLab.maxY + 5, tfW, height) WithTitle:@""];
    [self.view addSubview:_opponentLab];
    
    UIView *line2 = [self getLineWith:CGRectMake(0, _opponentLab.maxY + 2*labY - 1, kScreenWidth, 1)];
    [self.view addSubview:line2];
    
    UIView *sectionView2 = [ViewTool getLineViewWith:CGRectMake(0, line2.maxY, kScreenWidth, grayH) withBackgroudColor:GrayBackColor];
    [self.view addSubview:sectionView2];
    
    UIView *line3 = [self getLineWith:CGRectMake(0, sectionView2.maxY - 1, kScreenWidth, 1)];
    [self.view addSubview:line3];
    
    UIImageView *historyImg = [self imageWith:CGRectMake(startX, line3.maxY+ labY+1.5, imgW, imgW) withName:@"Btn_Normal_Lishi"];
    [self.view addSubview:historyImg];
    
    UILabel *historyLabel = [self getLabelWith:CGRectMake(labX, historyImg.y, labW, height) WithTitle:@"拜访历史"];
    [self.view addSubview:historyLabel];
    
    int role = [[[NSUserDefaults standardUserDefaults]  objectForKey:@"roleId"] intValue];
    if (role == 4) {
        addBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-20-imgW, historyImg.y, imgW, imgW)];
        [addBtn setImage:[UIImage imageNamed:@"Btn_Normal_Tianjia"] forState:UIControlStateNormal];
        [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:addBtn];
    }
    
    UIView *line4 = [self getLineWith:CGRectMake(labX, historyLabel.maxY + labY+1.5- 1, kScreenWidth-labX, 1)];
    [self.view addSubview:line4];
    
    _visitRecordArray = [NSMutableArray array];
    
    _visitRecordTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, line4.maxY, kScreenWidth, kScreenHeight-line4.maxY-64)];
    _visitRecordTableView.delegate = self;
    _visitRecordTableView.dataSource = self;
    _visitRecordTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
  
    [self.view addSubview:_visitRecordTableView];
    
    NSLog(@"sdlksjklksdjksl");
    [self initTableData];
}

- (void)setData{
    _subNameLab.text = _model.complex;
    _contactLab.text = _model.contact;
    _phoneLab.text = _model.tel;
    _areaLab.text = [NSString stringWithFormat:@"%@ %@ %@",_model.province,_model.city_name,_model.district_name];
    _addressLab.text = _model.complex_address;
    _proNameLab.text = _model.property;
    _opponentLab.text = _model.compete;
    
//    _visitRecordArray = _model.details;
//    _visitRecordTableView.height = TableCellHeight2*_model.details.count;
    NSMutableArray *arr = _model.details;
    
    if (_visitRecordArray.count > 0) {
        [_visitRecordArray removeAllObjects];
    }
    
    for(int i =0 ;i <arr.count;i++ ){
        VisitRecordModel *recordModel = [[VisitRecordModel alloc] init];
        NSDictionary *dci = arr[i];
        [recordModel setValuesForKeysWithDictionary:dci];
        [_visitRecordArray addObject:recordModel];
        if (_visitRecordArray.count == arr.count) {
            [_visitRecordTableView reloadData];
        }
        NSLog(@"数据描述++=====----%@",recordModel.desc);
    }
}

- (void)initTableData{
    [SVProgressHUD showWithStatus:@"加载中"];
    
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:@"app.visit.detail" forKey:@"method"];
    [dictionary setObject:@(_model.visit_id) forKey:@"visit_id"];
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dictionary] success:^(id data) {
        [SVProgressHUD dismiss];
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *status = [(NSDictionary *)jsonDic objectForKey:@"status"];
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"SUCCESS"]) {
            NSDictionary *info = [(NSDictionary *)jsonDic objectForKey:@"data"];
            NSDictionary * dataDict = [DataTool changeType:info];
            
            _model = [[VisitModel alloc] init];
            [_model setValuesForKeysWithDictionary:dataDict];
            [self setData];
            
        }else{
            NSString *code = [(NSDictionary *)jsonDic objectForKey:@"code"];
            NSString *msg = [(NSDictionary *)jsonDic objectForKey:@"msg"];
            NSLog(@"%@%@%@",status,code,msg);
            [Tools showMessage:msg view:self];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
        [Tools showMessage:@"数据获取失败" view:self];
    }];
}

- (void)setCellHeight:(NSIndexPath *)indexPath{
    
    if(selectedIndex==nil){
        selectedIndex=indexPath;
        [_visitRecordTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else{
        bool hasSelectedOtherRow=!(selectedIndex==indexPath);
        NSIndexPath *temp=selectedIndex;
        selectedIndex=nil;
        [_visitRecordTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:temp] withRowAnimation:UITableViewRowAnimationAutomatic];
        if(hasSelectedOtherRow){
            selectedIndex=indexPath;
            [_visitRecordTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
    
}

#pragma mark - UITableViewDataSource数据源方法
#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    for (int i=0; i<_visitRecordArray.count; i++) {
        [bCheck addObject:[NSNumber numberWithInt:0]];
    }
    return _visitRecordArray.count;
}

#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //NSIndexPath是一个对象，记录了组和行信息
    //    NSDictionary *records = _model.detail[indexPath.row];
//    VisitRecordModel *recordModel = [[VisitRecordModel alloc] init];
//    [recordModel setValuesForKeysWithDictionary:_visitRecordArray[indexPath.row]];

    VisitRecordModel *recordModel = _visitRecordArray[indexPath.row];
    NSLog(@"indexpath %d --- %@",indexPath.row,recordModel.desc);
    
    static NSString *CellIdentifier = @"VisitRecordTableViewCell";
//    VisitRecordTableViewCell *cell = (VisitRecordTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    VisitRecordTableViewCell *cell;
    if (cell == nil) {
       cell = [[VisitRecordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier VisitRecordModel:recordModel Frame:bounds];
        
        NSLog(@"1212121");
    }
    
//    else{
        [cell setRecordModel:recordModel];
//    }
    
    
    
//    NSLog(@"indexpath的row行数 +++++++------%ld  %@",(long)indexPath.row,cell.label.text);
//    MyButton * cellBtn= [cell returnBtn];
//        [cellBtn setTag:indexPath.row+20000];
//        [cellBtn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        //行高
    if (rowHight.count < _visitRecordArray.count){
        [rowHight addObject:[ NSNumber numberWithFloat:[cell returnRowHeight]]];
    }
        
//        UILabel * lab =cell.label;
//        [lab setTag:30000+indexPath.row ];
//        
//        UIView * picView =cell.picView;
//        [picView setTag:40000+indexPath.row ];
//        
//        UIView * bottomLine =cell.bottomLine;
//        [bottomLine setTag:50000+indexPath.row ];
//        UIView * leftLine2 =cell.leftLine2;
//        [leftLine2 setTag:60000+indexPath.row ];
//        UIImageView * quanImg =cell.quanImg;
//        [quanImg setTag:70000+indexPath.row ];
    
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    return cell;
    
}

-(void)click:(MyButton *)sender
{
    NSLog(@"click:%ld",(long)sender.tag);
    return;
    //初始化,所有单元格收缩到原始状态
    
    [bCheck removeAllObjects];
    
    for (int i=0; i<[rowHight count] ; i++) {
        [bCheck addObject:[NSNumber numberWithBool:NO]];
    }
    
    if (sender.isEXP) {
        [bCheck replaceObjectAtIndex:sender.tag-20000 withObject:[NSNumber numberWithInt:1]];
    }
    else{
        [bCheck replaceObjectAtIndex:sender.tag-20000 withObject:[NSNumber numberWithInt:0]];
    }
    
    
    for (int j=0; j<=rowHight.count; j++) {
        
        
        MyButton * dbtn=(MyButton *)[self.view viewWithTag:20000+j];
        
        if ([dbtn respondsToSelector:@selector(setBtnStatus:)]) {
            [dbtn setIsEXP:YES];
            [dbtn setBtnStatus:@"Btn_Normal_Jiantouxia"];
        }
        
        UILabel * llll = (UILabel *)[self.view viewWithTag:30000+j];
        
        llll.numberOfLines=2;
        llll.height = 40;
        dbtn.y = llll.maxY+5.0f;
        
        UIView * picView = (UIView *)[self.view viewWithTag:40000+j];
        picView.y = llll.maxY+5.0f;
        
        UIView * bottomLine = (UIView *)[self.view viewWithTag:50000+j];
        bottomLine.y = TableCellHeight2-1;
        
        UIView * quanImg = (UIView *)[self.view viewWithTag:70000+j];
        UIView * leftView = (UIView *)[self.view viewWithTag:60000+j];
        leftView.height = TableCellHeight2-quanImg.maxY-5.0f;
    }
    
    //选中行进行变化
    if( [bCheck objectAtIndex:sender.tag-20000]==[NSNumber numberWithInt:1])
        
    {
        NSLog(@"bCheck == 1");
        UILabel * llll = (UILabel *)[self.view viewWithTag:10000+sender.tag];
        
        llll.height = [[rowHight objectAtIndex:sender.tag-20000] floatValue];
        llll.numberOfLines=0;
        [llll sizeToFit];
        
        sender.y = llll.maxY+5.0f;
        
        [sender setBtnStatus:@"Btn_Normal_Jiantoushang"];
        [sender setIsEXP:NO];
        
        UIView * picView = (UIView *)[self.view viewWithTag:20000+sender.tag];
        picView.y = llll.maxY+5.0f;
        
        UIView * bottomLine = (UIView *)[self.view viewWithTag:30000+sender.tag];
        bottomLine.y = [[rowHight objectAtIndex:sender.tag-20000] floatValue]-1;
        
        UIView * quanImg = (UIView *)[self.view viewWithTag:50000+sender.tag];
        UIView * leftView = (UIView *)[self.view viewWithTag:40000+sender.tag];
        leftView.height = [[rowHight objectAtIndex:sender.tag-20000] floatValue]-quanImg.maxY-5.0f;
        
    }
    else{
        NSLog(@"bCheck != 1");
        UILabel * llll = (UILabel *)[self.view viewWithTag:10000+sender.tag];
        llll.numberOfLines=2;
        [llll sizeToFit];
        [sender setBtnStatus:@"Btn_Normal_Jiantouxia"];
        [sender setIsEXP:YES];
        sender.y = llll.maxY+5.0f;
        
        UIView * picView = (UIView *)[self.view viewWithTag:20000+sender.tag];
        picView.y = llll.maxY+5.0f;
        
        UIView * bottomLine = (UIView *)[self.view viewWithTag:30000+sender.tag];
        bottomLine.y = TableCellHeight2-1;
        
        UIView * quanImg = (UIView *)[self.view viewWithTag:50000+sender.tag];
        UIView * leftView = (UIView *)[self.view viewWithTag:40000+sender.tag];
        leftView.height = TableCellHeight2-quanImg.maxY-5.0f;
        
    }
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:sender.tag-20000 inSection:0];
    
    [_visitRecordTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
//    [_visitRecordTableView reloadData];
    
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([bCheck objectAtIndex:indexPath.row]==[NSNumber numberWithInt:1]) {
        
        return [[rowHight objectAtIndex:indexPath.row] floatValue];
    }else{
        
        return TableCellHeight2;
    }
}

/// 处理单元格点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RecordDetailViewController *recoredVC = [[RecordDetailViewController alloc] init];
    recoredVC.recordModel = _visitRecordArray[indexPath.row];
    [self.navigationController pushViewController:recoredVC animated:YES];
}

#pragma mark - UIViewSetting
- (UIImageView *)imageWith:(CGRect)frame withName:(NSString *)str{
    UIImageView *img = [[UIImageView alloc]initWithFrame:frame];
    img.image = [UIImage imageNamed:str];
    return img;
}
- (UILabel *)getLabelWith:(CGRect)frame WithTitle:(NSString *)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = title;
    label.textColor = BLACKCOLOR;
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [ViewTool getFont:16.0f];
    return label;
}
- (UILabel *)getLabelWith:(CGRect)frame WithTitle:(NSString *)title WithFontSize:(CGFloat)fontSize WithTitleColor:(UIColor *)color WithTextAlignment:(NSTextAlignment )textAlignment
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = title;
    label.textColor = color;
    label.textAlignment = textAlignment;
    label.font = [ViewTool getFont:fontSize];
    return label;
}

-(UIView *)getLineWith:(CGRect)frame
{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = GRAYLINECOLOR;
    return view;
}

- (void)goToBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}
//编辑界面
-(void)addBtnClick:(UIButton *)btn
{
    AddRecordViewController * vc=[[AddRecordViewController alloc]init];
    vc.model = self.model;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)passValue:(NSString *)value{
    if ([value isEqualToString:@"SUCCESS"]) {
        [self initTableData];
    }
}

@end
